package com.yzkj.framework.core.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.List;

/**
 * 邮件发送工具类
 *
 * @author Skye
 */
@Component
public class EmailHelper {

    @Autowired
    private JavaMailSender mailSender;

    /**
     * 发送简单文本邮件
     *
     * @param subject   主题
     * @param content   内容
     * @param filePaths 附件路径列表
     * @param to        目的地
     * @throws MessagingException
     */
    public void sendMail(String from, String subject, String content, List<String> filePaths, Boolean html, String... to)
            throws MessagingException {

        MimeMessage message = mailSender.createMimeMessage();

        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(content, html);
        helper.setFrom(from);
        if (filePaths != null && filePaths.size() > 0) {
            for (String filePath : filePaths) {
                FileSystemResource file = new FileSystemResource(new File(filePath));
                String fileName = file.getFilename();
                if (fileName == null) {
                    fileName = RandomUtils.createSimpleUUID();
                }
                helper.addAttachment(fileName, file);
            }
        }

        mailSender.send(message);
    }

    /**
     * 发送html邮件
     *
     * @param subject 主题
     * @param content 内容
     * @param to      目的地
     * @throws MessagingException
     */
    public void sendHtmlEmail(String from, String subject, String content, String... to) throws MessagingException {

        this.sendMail(from, subject, content, null, true, to);

    }

    /**
     * 发送简单文本邮件
     *
     * @param subject 主题
     * @param content 内容
     * @param to      目的地
     * @throws MessagingException
     */
    public void sendTextMail(String from, String subject, String content, String... to) throws MessagingException {

        this.sendMail(from, subject, content, null, false, to);
    }
}
